package com.qms.tubu.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.qms.tubu.R;
import com.qms.tubu.activity.account.LoginActivity;
import com.qms.tubu.activity.account.PersonalActivity;
import com.qms.tubu.activity.search.SearchActivity;
import com.qms.tubu.application.TubuApplication;
import com.qms.tubu.dialog.ExPopupWindow;
import com.qms.tubu.fragment.RecommendationFragment;
import com.qms.tubu.fragment.account.DrawerLoginFragment;
import com.qms.tubu.fragment.account.DrawerLogoutFragment;
import com.qms.tubu.fragment.date.DateFragment;

import org.w3c.dom.Text;

/**
 * Created by Mad on 2015/7/2.
 */
public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener,
        TubuApplication.OnAccountChangeListener,View.OnClickListener,BDLocationListener{
    private DrawerLayout mDrawer;
    private View mDrawerLogoView;
    private ScrollView mNavigationView;
    private RadioGroup mRadioGroup;
    private RecommendationFragment mRecommendationFragment;
    private DateFragment mDateFragment;
    private Fragment mCurrFragment;
    private View mDateSpinner;
    private LocationClient mLocationClient;
    private BDLocation mLocation;
    private TextView mMyLocationText;
    private MenuItem mAddDateItem;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        findView();
        initDrawer();
        initData();
        addDateSpinner();
        initLocationClient();
        mRadioGroup.setOnCheckedChangeListener(this);
        mRadioGroup.check(R.id.main_recommend_radio_btn);
        setNavigationPaddingTop();
        checkAccount(getTubuApplication().getAccount() != null);
        getTubuApplication().addChangeListener(this);
    }

    private void initLocationClient()
    {
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setIsNeedAddress(true);
        option.setIsNeedLocationDescribe(false);
        option.setIsNeedLocationPoiList(false);
        mLocationClient=new LocationClient(this,option);
        mLocationClient.registerLocationListener(this);
    }
    private void setNavigationPaddingTop()
    {
        if(Build.VERSION.SDK_INT>18)
        {
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if(resourceId>0)
            {
                int statusBarHeight=getResources().getDimensionPixelOffset(resourceId);
                mNavigationView.setPadding(0,statusBarHeight,0,0);
            }
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.main_search_btn:
                startActivity(new Intent(this, SearchActivity.class));
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.main_menu,menu);
        mAddDateItem=menu.findItem(R.id.main_add_date_btn);
        mAddDateItem.setVisible(false);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        if(bdLocation.getLocType()==BDLocation.TypeNetWorkLocation || bdLocation.getLocType()==BDLocation.TypeGpsLocation)
        {
            mLocation=bdLocation;
            mMyLocationText.setText(mLocation.getProvince()+mLocation.getCity());
            mLocationClient.stop();
        }
    }

    public BDLocation getLocation() {
        return mLocation;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mLocationClient.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mLocationClient.stop();
    }

    private void findView()
    {
        mDrawer= (DrawerLayout) this.findViewById(R.id.main_drawer);
        mRadioGroup= (RadioGroup) this.findViewById(R.id.main_radio_group);
        mNavigationView= (ScrollView) this.findViewById(R.id.main_navigation_view);
        mMyLocationText= (TextView) this.findViewById(R.id.main_drawer_my_location_text);
    }
    private void initData()
    {
        this.findViewById(R.id.drawer_menu_personal_btn).setOnClickListener(this);
    }
    @Override
    public void onBackPressed() {
        if(mDrawer.isDrawerOpen(Gravity.LEFT))
        {
            mDrawer.closeDrawer(Gravity.LEFT);
            return ;
        }
        super.onBackPressed();
    }
    private void addDateSpinner()
    {
        mDateSpinner=getLayoutInflater().inflate(R.layout.main_date_spinner,null);
        Toolbar.LayoutParams params=new Toolbar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        TextView textView= (TextView) mDateSpinner.findViewById(R.id.date_spinner_text);
//        int unicode = 0xd83d;
//        textView.setText(new String(Character.toChars(unicode)));
        params.gravity=Gravity.CENTER;
        mToolbar.addView(mDateSpinner,params);
//        mDateSpinner.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                View popupView=getLayoutInflater().inflate(R.layout.date_spinner_popup,null);
//                ExPopupWindow popupWindow=new ExPopupWindow(popupView);
//                PopupWindowCompat.showAsDropDown(popupWindow,mToolbar,0,0,Gravity.NO_GRAVITY);
//            }
//        });
        mDateSpinner.setVisibility(View.GONE);
    }
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
        if(mCurrFragment!=null)
            transaction.hide(mCurrFragment);
        if(checkedId==R.id.main_date_radio_btn) {
            if(mAddDateItem!=null)
                mAddDateItem.setVisible(true);
            mDateSpinner.setVisibility(View.VISIBLE);
        }
        else {
            if(mAddDateItem!=null)
                mAddDateItem.setVisible(false);
            mDateSpinner.setVisibility(View.GONE);
        }
        switch (checkedId)
        {
            case R.id.main_recommend_radio_btn:
                if(mRecommendationFragment==null)
                {
                    mRecommendationFragment=new RecommendationFragment();
                    transaction.add(R.id.main_fragment_container,mRecommendationFragment);
                }
                else
                    transaction.show(mRecommendationFragment);
                mCurrFragment=mRecommendationFragment;
                break;
            case R.id.main_date_radio_btn:
                if(mDateFragment==null)
                {
                    mDateFragment=new DateFragment();
                    transaction.add(R.id.main_fragment_container,mDateFragment);
                }
                else
                    transaction.show(mDateFragment);
                mCurrFragment=mDateFragment;
                break;
        }
        transaction.commit();
    }

    private void initDrawer()
    {
        ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,mDrawer,R.string.drawer_open_content,R.string.drawer_close_content);
        mDrawer.setDrawerListener(toggle);
        toggle.syncState();
        mDrawerLogoView=getLayoutInflater().inflate(R.layout.main_drawer_logo,null);
        mToolbar.addView(mDrawerLogoView);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        mDrawerLogoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawer.openDrawer(Gravity.LEFT);
            }
        });
    }

    public View getDateSpinner() {
        return mDateSpinner;
    }

    @Override
    public void onClick(View v) {
        Intent intent=null;
        if(getTubuApplication().getAccount()==null)
            intent=new Intent(this, LoginActivity.class);
        else {
            switch (v.getId())
            {
                case R.id.drawer_menu_personal_btn:
                    intent=new Intent(this, PersonalActivity.class);
                    break;
            }
        }
        startActivity(intent);
    }

    private void checkAccount(boolean state)
    {
        FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
        if(state)
            transaction.replace(R.id.drawer_fragment_container,new DrawerLoginFragment(),"login");
        else
            transaction.replace(R.id.drawer_fragment_container,new DrawerLogoutFragment(),"logout");
        transaction.commitAllowingStateLoss();
    }

    @Override
    protected void onDestroy() {
        mLocationClient.unRegisterLocationListener(this);
        getTubuApplication().removeChangeListener(this);
        super.onDestroy();
    }

    @Override
    public void onDataChanged() {

    }
    @Override
    public void onSignStateChanged(boolean signState) {
        checkAccount(signState);
    }
}
